package com.atguigu.day03;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//信号灯Semaphore
//以停车位为例，假设共有三个停车位，一个车来停，信号灯就要减一，表示可用资源减少一，
// 一个车走了，信号灯加一，表示有新资源，可用资源加一
public class SemaphoreDemo {
    public static void main(String[] args) {
        //假设有三个停车位
        Semaphore semphore = new Semaphore(3);

            for (int i = 1; i <= 6; i++) {

                new Thread(() -> {
                    try {
                    try {
                        semphore.acquire();
                        System.out.println(Thread.currentThread().getName()+"抢到车位了");
                        //线程睡眠几秒
                        try {
                            TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {throw new RuntimeException(e);}
                        System.out.println(Thread.currentThread().getName()+"该车位使用完毕");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }finally {
                        semphore.release();
                    }

                }, String.valueOf(i)).start();
            }



    }
}
